import threadpool

class Base(object):
    def write(self, text):
        f = codecs.open(
            self.__class__.__name__.lower() + '.log',
            'a', 'utf-8' )
        f.write(text)
        f.close()
    def prt(self, msg):
        errmsg = '[%s] %s' % (
            self.__class__.__name__.lower(),
            msg or '')
        print(errmsg)
    def log(self, msg):
        errmsg = '[%s] %s\n' % (
            self.__class__.__name__.lower(),
            msg or '')
        self.write(errmsg)
    def logp(self, msg):
        errmsg = '[%s] %s' % (
            self.__class__.__name__.lower(),
            msg or '')
        print(errmsg)
        self.write(errmsg + '\n')
    def strip(self, text):
        return re.sub(r'\s+','', text)
    def url_remove_param(self, url):
        return re.sub(r'(\?[a-zA-Z0-9&=]+)?','', url)
    def create_file(self, file, content=u''):
        if os.path.exists(file):
            return False
        path = os.path.dirname(file)
        self.mkdirs(path)
        #
        fp = codecs.open(file, 'w', 'utf-8')
        fp.write(content)
        fp.close()

        return True
    def mkdirs(self, path):
        try:
            os.makedirs(path)
        except:
            pass
    def del_empty_line(self, text):
        return re.sub(r'\n[\s| ]*\n', '', text)

class Task(Base):
    def __init__(self, threads=4, tasks=0):
        self.pool = threadpool.ThreadPool(threads, tasks)
    def put(self, fun, *args, **kwargs):
        def _fun(self):
            return fun(self, *args, **kwargs)
        reqs = threadpool.makeRequests(_fun, [self])
        [ self.pool.putRequest(req) for req in reqs ]
        self.prt('put task : %s' % (fun.__name__.lower()))
#-----------#
